#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define BUFSIZE 1024

void error_handling(char *message) {
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

void write_routine(int sock, char *buf) {
    while (1) {
        fgets(buf, BUFSIZE, stdin);
        if (strcmp(buf, "q\n") == 0) {
            // 这里只能关闭写端传递EOF 而且不能一次close传递EOF 需要两次close
            shutdown(sock, SHUT_WR);
            break;
        }
        write(sock, buf, strlen(buf));
    }
}

void read_routine(int sock, char *buf) {
    while (1) {
        int str_len = read(sock, buf, BUFSIZE);
        if (str_len == 0)
            return;
        buf[str_len] = 0;
        printf("Message from server: %s", buf);
    }
}

int main(int argc, char *argv[]) {
    int client_sock;
    char buf[BUFSIZE];
    if (argc != 3) {
        printf("Usage : %s <IP> <port>\n", argv[0]);
        exit(1);
    }
    if ((client_sock = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
        error_handling("socket() error!");
    }
    
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(argv[1]);
    server_addr.sin_port = htons(atoi(argv[2]));

    if (connect(client_sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        error_handling("connect() error!");
    } else {
        puts("connecting.......");
    }

    pid_t pid = fork();
    if (pid == 0) {
        write_routine(client_sock, buf);
    } else {
        read_routine(client_sock, buf);
    }
    close(client_sock);
    return 0;
}